<template>
  <div class="score-list-container">
    <div class="header">
      <h2>成绩查询</h2>
      <div class="actions">
        <el-select v-model="queryParams.subjectId" placeholder="选择科目" clearable>
          <el-option
            v-for="subject in subjectOptions"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"
          />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="handleDateChange"
        />
        
        <el-button type="primary" @click="fetchScoreList">查询</el-button>
      </div>
    </div>
    
    <div class="content" >
      <el-table
        v-loading="loading"
        :data="scoreList"
        border
        stripe
      >
        <el-table-column label="考试名称" prop="examinationName" width="auto" />
        <el-table-column label="科目" prop="subjectName" width="100" />
        <el-table-column label="考试时间" width="auto">
          <template #default="{ row }">
            {{ formatDate(row.examTime) }}
          </template>
        </el-table-column>
        <el-table-column label="成绩" width="120">
          <template #default="{ row }">
            <span 
              class="score" 
              :class="getScoreClass(row.score, row.totalScore)"
            >
              {{ row.score }}/{{ row.totalScore }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="得分率" width="100">
          <template #default="{ row }">
            <el-progress 
              :percentage="getScorePercentage(row.score, row.totalScore)" 
              :status="getProgressStatus(row.score, row.totalScore)"
            />
          </template>
        </el-table-column>
        <el-table-column label="排名" width="auto">
          <template #default="{ row }">
            <template v-if="row.rank && row.totalStudents">
              {{ row.rank }}/{{ row.totalStudents }}
              <span class="rank-label">({{ formatRankPercentile(row.rank, row.totalStudents) }})</span>
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewScoreDetail(row.id)">
              查看详情
            </el-button>
            <!-- <el-button type="success" link @click="downloadReport(row.id)">
              下载报告
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="scoreList.length === 0 && !loading" description="暂无成绩记录" />
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      
    </div>
    
    <!-- 成绩趋势 -->
    <div class="score-trend" v-if="scoreList.length > 0">
      <h3>成绩趋势</h3>
      <div ref="trendChart" class="trend-chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getScoreList } from '@/api/student/score'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  LineChart, GridComponent, TooltipComponent, 
  TitleComponent, LegendComponent, CanvasRenderer
])

const router = useRouter()
const loading = ref(false)
const total = ref(0)
const scoreList = ref([])
const dateRange = ref(null)
const trendChart = ref(null)

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  subjectId: '',
  startTime: '',
  endTime: ''
})

// 学科选项
const subjectOptions = ref([
  { id: 1, name: '数学' },
  { id: 2, name: '语文' },
  { id: 3, name: '英语' }
])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 日期变化处理
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    queryParams.startTime = formatDateParam(dates[0])
    queryParams.endTime = formatDateParam(dates[1])
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}

// 格式化日期参数
const formatDateParam = (date) => {
  if (!date) return ''
  
  const year = date.getFullYear()
  const month = padZero(date.getMonth() + 1)
  const day = padZero(date.getDate())
  
  return `${year}-${month}-${day}`
}

// 获取成绩列表
const fetchScoreList = async () => {
  loading.value = true
  
  try {
    const { data } = await getScoreList(queryParams)
    scoreList.value = data.list
    total.value = data.total
    
    // 初始化图表
    nextTick(() => {
      initTrendChart()
    })
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    ElMessage.error('获取成绩列表失败')
    scoreList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchScoreList()
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.limit = size
  queryParams.page = 1
  fetchScoreList()
}

// 查看成绩详情
const viewScoreDetail = (id) => {
  router.push(`/score/${id}`)
}

// 下载成绩报告
const downloadReport = async (id) => {
  try {
    await ElMessageBox.confirm('确定要下载该成绩报告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    // TODO: 实现报告下载逻辑
    ElMessage.success('报告下载成功')
  } catch {
    // 取消下载
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '--'
  
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

// 补零
const padZero = (num) => {
  return num < 10 ? `0${num}` : num
}

// 获取分数百分比
const getScorePercentage = (score, totalScore) => {
  if (!totalScore) return 0
  return Math.round((score / totalScore) * 100)
}

// 获取进度条状态
const getProgressStatus = (score, totalScore) => {
  const percentage = getScorePercentage(score, totalScore)
  
  if (percentage >= 90) return 'success'
  if (percentage >= 60) return ''
  return 'exception'
}

// 获取分数样式
const getScoreClass = (score, totalScore) => {
  const percentage = getScorePercentage(score, totalScore)
  
  if (percentage >= 90) return 'excellent'
  if (percentage >= 80) return 'good'
  if (percentage >= 60) return 'pass'
  return 'fail'
}

// 格式化排名百分位
const formatRankPercentile = (rank, total) => {
  if (!rank || !total || total === 0) return '--'
  
  const percentage = Math.round((rank / total) * 100)
  
  if (percentage <= 5) return '前5%'
  if (percentage <= 10) return '前10%'
  if (percentage <= 20) return '前20%'
  if (percentage <= 50) return '前50%'
  return '后50%'
}

// 初始化趋势图
const initTrendChart = () => {
  const chartDom = document.querySelector('.trend-chart')
  if (!chartDom || scoreList.value.length === 0) return
  
  const chart = echarts.init(chartDom)
  
  // 按时间排序
  const sortedList = [...scoreList.value].sort((a, b) => 
    new Date(a.examTime) - new Date(b.examTime)
  )
  
  // 准备数据
  const xAxis = sortedList.map(item => {
    // 仅显示日期部分
    const date = new Date(item.examTime)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  const scoreData = sortedList.map(item => {
    return getScorePercentage(item.score, item.totalScore)
  })
  
  const rankData = sortedList.map(item => {
    if (!item.rank || !item.totalStudents) return null
    return Math.round(100 - (item.rank / item.totalStudents * 100))
  })
  
  const option = {
    title: {
      text: '成绩趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['得分率', '排名百分位'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxis
    },
    yAxis: [
      {
        type: 'value',
        name: '得分率(%)',
        min: 0,
        max: 100
      }
    ],
    series: [
      {
        name: '得分率',
        type: 'line',
        data: scoreData,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '排名百分位',
        type: 'line',
        data: rankData,
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

onMounted(() => {
  fetchScoreList()
})
</script>

<style scoped>
.score-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.actions {
  display: flex;
  gap: 16px;
}

.content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score {
  font-weight: bold;
}

.score.excellent {
  color: #67C23A;
}

.score.good {
  color: #409EFF;
}

.score.pass {
  color: #E6A23C;
}

.score.fail {
  color: #F56C6C;
}

.rank-label {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.score-trend {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.score-trend h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #303133;
  text-align: center;
}

.trend-chart {
  height: 350px;
  width: 100%;
}
</style> 